require 'digest/md5'

class UserController < ApplicationController
	def new
		@user = User.new
	end
	
	def index
	end
	
    #def register_error
    #end
 
	def register
		@title = "Register"
		if request.post?
			@user = User.new(params[:user])
			if User.find(:first, :conditions => [ "mail = ?", @user.mail])
                flash[:error] = "This email is already in use"
				redirect_to :action => :register and return
			end
			@user.password = Digest::MD5.hexdigest(@user.password)
			@user.inscription_date = Date::today();
			@user.last_login = Date::today();
			if @user.save
				flash[:success] = "User with login #{@user.first_name} created successfully!"
				redirect_to :action => :index
			else
				flash[:error] = "Bad mail or too small password (length must be at least 6) or names too small (length must be at least 2)"
			end
		end
	end
	
	def login
		if request.post?
			if @user = User.find_by_mail_and_password(params[:user][:mail], Digest::MD5.hexdigest(params[:user][:password]))
				flash[:success] = "User with mail #{@user.mail} logged successfully!"
				session[:user] = @user.id;
				redirect_to root_url
			else
				flash[:error] = "Wrong password/mail"
			end
		end
	end
	
	def logout
		session[:user] = nil
		redirect_to root_url
	end
	
	def view
		@user = User.find(params[:id])
	end
	
	def profile
		@user_info = User.find(session[:user]).user_info
		if !@user_info
			flash[:notice] = "Your profile is empty you might want to fill it !"
			redirect_to user_edit_path
		end
	end
	
	def edit
		@user = User.find(session[:user])
		puts "toto"
		@user_info = @user.user_info
		if request.post?
			if !@user_info
				if !@user.build_user_info(params[:user_info])
					flash[:error] = "Bad values ! Or Used Login !"
				else
					@user.save
					flash[:success] = "Your profile was edited successfully!"
					redirect_to user_profile_path
				end
			else
				@user_info = @user.user_info
				if @user_info.login != params[:user_info][:login]
					@user_info.login = params[:user_info][:login]
				end
				@user_info.age = params[:user_info][:age]
				 @user_info.country = params[:user_info][:country]
				 @user_info.city = params[:user_info][:city]
				 @user_info.postal_code = params[:user_info][:postal_code]
				 if @user_info.save
					 flash[:notice] = "Your profile was edited successfully!"
					 redirect_to user_profile_path
				 end
			end
		end
	end
end
